package com.example.xplayer

import android.Manifest
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.xplayer.ui.theme.XPlayerTheme

class MainActivity : ComponentActivity() {
    // 权限请求码
    private val REQUEST_STORAGE_PERMISSIONS = 1001

    // 根据系统版本适配权限
    private val requiredPermissions: Array<String>
        get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arrayOf(Manifest.permission.READ_MEDIA_VIDEO)
        } else {
            arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        // 初始化时检查权限
        checkStoragePermissions()

        setContent {
            XPlayerTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    MainScreen(
                        modifier = Modifier.padding(innerPadding),
                        onEnterPlayer = {
                            // 点击进入播放器前再次检查权限
                            if (checkStoragePermissions()) {
                                navigateToPlayer()
                            }
                        }
                    )
                }
            }
        }
    }

    // 检查存储权限，返回是否已授予
    private fun checkStoragePermissions(): Boolean {
        val allGranted = requiredPermissions.all { permission ->
            ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
        }

        if (!allGranted) {
            // 未授予权限，发起请求
            ActivityCompat.requestPermissions(
                this,
                requiredPermissions,
                REQUEST_STORAGE_PERMISSIONS
            )
            return false
        }
        return true
    }

    // 处理权限请求结果
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_STORAGE_PERMISSIONS) {
            val allGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }
            if (allGranted) {
                Toast.makeText(this, "存储权限已授予，可进入播放器", Toast.LENGTH_SHORT).show()
            } else {
                // 权限被拒绝，显示引导对话框
                showPermissionGuideDialog()
            }
        }
    }

    // 权限引导对话框
    private fun showPermissionGuideDialog() {
        AlertDialog.Builder(this)
            .setTitle("权限必需")
            .setMessage("播放本地视频需要存储权限，请前往设置开启")
            .setPositiveButton("去设置") { _, _ ->
                val intent = Intent(
                    Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                    android.net.Uri.fromParts("package", packageName, null)
                )
                startActivity(intent)
            }
            .setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss()
            }
            .show()
    }

    // 跳转到播放器页面
    private fun navigateToPlayer() {
        val intent = Intent(this, PlayerActivity::class.java)
        startActivity(intent)
    }
}

// 主界面组件
@Composable
fun MainScreen(
    modifier: Modifier = Modifier,
    onEnterPlayer: () -> Unit
) {
    Column(
        modifier = modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = "欢迎使用视频播放器",
            fontSize = 20.sp,
            modifier = Modifier.padding(bottom = 30.dp)
        )

        Button(
            onClick = onEnterPlayer,
            modifier = Modifier
                .size(width = 200.dp, height = 50.dp)
        ) {
            Text(text = "进入播放器", fontSize = 16.sp)
        }
    }
}

@Preview(showBackground = true)
@Composable
fun MainScreenPreview() {
    XPlayerTheme {
        MainScreen(onEnterPlayer = {})
    }
}